package com.nl.controller.web.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.CRMOpenInfo;
import com.nl.controller.web.bean.SmsMgrGovernmentInfo;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.CRMFindMgr.MgrInfo;
import com.nl.controller.web.mapper.CRMMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CRMInterfaceService {
	
	@Autowired
	private CommonMapper commonMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private CRMMapper cRMMapper;
	
	private final String jZZWUrl="";//精准政务开户信息同步

	@SystemServiceLog(description = "CRM项目名称联想", value = false)
	public Map<String, Object> selectMgrNameLike(String cRMReqMgrList) {
			String resultDesc="";
			String sendNumber;
			 List<MgrInfo> mgrInfoList = new ArrayList<>();
	        Map<String, Object> retMap=new HashMap<String, Object>();
	        try{
	        if(cRMReqMgrList!=null&&!"".equals(cRMReqMgrList)){
	        	JSONObject jsonObject=JSONObject.parseObject(cRMReqMgrList);
	        	String channel = jsonObject.getString("channel");
	            log.info("【CRM项目信息查询】请求渠道：{}",channel);
	            String key=jsonObject.getString("mgrName");      
	            log.info("【CRM项目信息查询】项目名称联想：{}",key);
	            String streamSeq = jsonObject.getString("streamSeq");
	            log.info("【CRM项目信息查询】流水号：{}",streamSeq);
	            if(key!=null && key.length()>1){
		            List<SmsMgrInfo> list;
		            List<SmsMgrGovernmentInfo> listG;
		            list = commonService.selectMgrNameLike(key,"","");
		            listG = commonService.selectMgrNameLikeG(key);
		            for (SmsMgrInfo smsMgrInfo : list) {
		            	if("11".equals(smsMgrInfo.getCityId())){
		                    sendNumber="106571103"+"1"+smsMgrInfo.getCityExtId();     
		            	}else{
		            		sendNumber="106571102"+"1"+smsMgrInfo.getCityExtId();
		            	}
		            	String mgrName = smsMgrInfo.getName();
		            	MgrInfo mgrInfo = new MgrInfo();
		            	mgrInfo.setSendNumber(sendNumber);
		            	mgrInfo.setMgrName(mgrName);
		            	mgrInfoList.add(mgrInfo);
					}
		            for (SmsMgrGovernmentInfo smsMgrGovernmentInfo : listG) {
		            	String mgrNameG = smsMgrGovernmentInfo.getMgrName();
		            	String sendNumberG = smsMgrGovernmentInfo.getSendNumber();
		            	MgrInfo mgrInfo = new MgrInfo();
		            	mgrInfo.setSendNumber(sendNumberG);
		            	mgrInfo.setMgrName(mgrNameG);
		            	mgrInfoList.add(mgrInfo);
					}
	            }       
	            retMap.put("channel", channel);
	            retMap.put("mgrInfo", mgrInfoList);
	            retMap.put("streamSeq", streamSeq);
	        }
	        }
	        catch(Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				resultDesc="CRM项目名称联想接口异常,error:"+e.getMessage();
				e.printStackTrace();
				log.info("调用CRM项目名称联想接口失败");
				retMap.put("resultDesc", resultDesc);
			}
	        return retMap;
	}
	
	@SystemServiceLog(description = "CRM开户信息同步", value = false)
	public Map<String, Object> addOpenInfo(String cRMOpenInfo) {
		CRMOpenInfo crmOpenInfo = JSON.parseObject(cRMOpenInfo,CRMOpenInfo.class);	
		String resultCode="-1";
		String resultDesc="失败";
		int result;
		String sendNumber;
		Map<String, Object> retMap=new HashMap<String, Object>();
		try{      
	        	String channel = crmOpenInfo.getChannel();
	            log.info("【CRM开户信息同步】请求渠道：{}",channel);           	            
	            String streamSeq = crmOpenInfo.getStreamSeq();
	            log.info("【CRM开户信息同步】流水号：{}",streamSeq);
	              sendNumber = crmOpenInfo.getSendNumber();
	            log.info("【CRM开户信息同步】短信通道号：{}",sendNumber);
	            
	            if("1".equals(channel)){
	            result = cRMMapper.addOpenInfo(crmOpenInfo);
	            log.info("【CRM开户信息同步】",result);
	            if(result==1){
	             resultCode="0";
	             resultDesc ="成功";
	            }
	 	        retMap.put("channel", channel);
	 	        retMap.put("streamSeq", streamSeq);  
	            }
	         // 匹配精准政务
	             JZZW(cRMOpenInfo);
	        }catch(Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				resultDesc="CRM开户信息同步接口异常,error:"+e.getMessage();
				e.printStackTrace();
				log.info("调用CRM开户信息同步接口失败");
			}
		    retMap.put("resultCode", resultCode);
	        retMap.put("resultDesc", resultDesc); 
	        return retMap;
	}
	
	// 匹配精准政务
	public /*void*/Map<String, Object> JZZW(String cRMOpenInfo){
		JSONObject json = JSON.parseObject(cRMOpenInfo);	
    	String sendNumber = json.getString("sendNumber");
    	JSONObject req = JSONObject.parseObject(new String(cRMOpenInfo));
        String resp="";
        Map<String, Object> retMapJ=new HashMap<String, Object>();
		try{	
			String jSendNumber = sendNumber.substring(0, 8);
			if ("10657016".equals(jSendNumber)) {
				resp = this.httpPostWithJSON(jZZWUrl, req);
				//resp ="{\"resultCode\": \"0\", 	\"resultDesc\": \"成功\", 	\"streamSeq\": \"20190809110306100001\"}" ;
				//解压
				/*log.info("精准政务开户信息同步接口回参(解压前)：{}", resp);
				resp = GZipUtil.gunzip(resp);
				log.info("精准政务开户信息同步接口回参(解压后)：{}", resp);*/
				log.info("精准政务开户信息同步接口回参", resp);
				retMapJ = this.readJZZWResp(resp);
				commonService.createSmsOperLog("6","0","精准政务开户信息同步接口", "0", "17");
			}
		}catch(Exception e) {
			    e.printStackTrace();
	            commonService.createSmsOperLog("6","0", "精准政务开户信息同步接口", "1", "17");
	            log.error("精准政务开户信息同步接口");
	            throw new SmsException("精准政务开户信息同步接口异常");
		}
       	return retMapJ;
	}
	
	public String httpPostWithJSON(String url, JSONObject jsonParam)
            throws Exception {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        org.apache.http.HttpEntity entity = null;
        String result = "";
        try {
            httpclient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            StringEntity entityParam = new StringEntity(jsonParam.toString(),
                    "utf-8");// 解决中文乱码问题
            entityParam.setContentEncoding("UTF-8");
            entityParam.setContentType("application/json");
            httpPost.setEntity(entityParam);
            // 设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
                    20000);
            // 设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 20000);
            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } 
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }
	
	private Map<String, Object> readJZZWResp(String resp){
        String resultCode="-1";
        String resultDesc="失败";
        String streamSeq = "";
        Map<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);       	
        	resultCode = jsonObject.getString("resultCode");
            resultDesc = jsonObject.getString("resultDesc");
        	streamSeq = jsonObject.getString("streamSeq");
        }
        retMap.put("resultCode", resultCode);
        retMap.put("resultDesc", resultDesc);        
        retMap.put("streamSeq", streamSeq);
        return retMap;
	}
}
